import os
from datetime import date

import requests


class BingHud:
    def __init__(self):
        self.url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=ZH-CN'
        self.path = './bg/'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/80.0.3987.132 Safari/537.36'
        }
        self.resolution = 'UHD'

    def get_image_info(self):
        result = requests.get(self.url, headers=self.headers).json()

        # 提取图片地址
        raw_img_url = 'https://cn.bing.com' + result['images'][0]['url']

        # 得到普通图片地址
        normal_img_url = raw_img_url[0:raw_img_url.find('.jpg') + 4]

        # 得到UHD图片链接替换默认的 1080 图片为UHD图片链接
        uhd_img_url = normal_img_url.replace('1920x1080', self.resolution)

        # 提取中文标题和版权信息
        date = result["images"][0]["startdate"]
        title = result["images"][0]["title"]
        copy_right = result["images"][0]["copyright"]

        print("日期：", date)
        print("标题：", title)
        print("版权：", copy_right)
        print("图片链接：", normal_img_url)

        return normal_img_url, uhd_img_url

    def download_image(self, url, file_name):
        response = requests.get(url, stream=True)

        path = "D:\\bingImage\\" + date.today().strftime("%Y-%m-%d")
        # 判断文件夹是否存在
        if not os.path.exists(path):
            os.makedirs(path)

        if response.status_code == 200:
            with open(path + "\\" + file_name, 'wb') as f:
                f.write(response.content)
                f.close()
                print("图片下载成功")
        else:
            print("图片下载失败")

if __name__ == '__main__':
    bing = BingHud()
    info = bing.get_image_info()
    # 下载普通照片
    bing.download_image(info[0], 'bg.jpg')
    # 下载UHD照片
    bing.download_image(info[1], 'bg_uhd.jpg')